<template>
	<view class="content">
		<!-- 顶部导航栏 -->
		<u-navbar bgColor="#F5F9FC" :placeholder="true" :border="true" height="48px">
			<view slot="left" class="navbar-left">
				<navigator url="/pages/index/index" open-type="switchTab" class="back-button">
					<view class="nav-back-content">
						<u-icon color="#1e88e5" name="arrow-left"></u-icon>
						<view class="nav-title">发票管理</view>
					</view>
				</navigator>
			</view>
			<view slot="right" class="navbar-right">
			</view>
		</u-navbar>

		<!-- 搜索框 - 位于标签页上方 -->
		<view class="search-container">
			<view class="search-box">
				<u-icon name="search" color="#999" size="24rpx" class="search-icon"></u-icon>
				<input type="text" placeholder="搜索发票信息" v-model="searchKeyword" class="search-input" />
			</view>
		</view>

		<!-- 标签页（固定，与接口类别映射） -->
		<view class="custom-tabs">
			<view class="tab-item" :class="{ active: currentTab === 0 }" @click="switchTab(0)">
				<text>开出票据</text>
			</view>
			<view class="tab-item" :class="{ active: currentTab === 1 }" @click="switchTab(1)">
				<text>收到票据</text>
			</view>
			<view class="tab-item" :class="{ active: currentTab === 2 }" @click="switchTab(2)">
				<text>费用票据</text>
			</view>
		</view>

		<!-- 筛选栏 -->
		<view class="filter-container">
			<view class="filter-left">
				<view class="date-filter" @click="showDatePicker = true">
					<text>{{ formatSelectedDate() }}</text>
					<u-icon name="arrow-down" size="14" color="#666"></u-icon>
				</view>
				<view class="type-filter" @click="showTypePicker = true">
					<text>发票种类</text>
					<u-icon name="arrow-down" size="14" color="#666"></u-icon>
				</view>
			</view>
			<view class="filter-right">
				<view class="search-btn" @click="handleSearch">
					<text>搜索</text>
				</view>
				<view class="export-btn" @click="handleExport">
					<text>导出</text>
				</view>
			</view>
		</view>

		<!-- 统计信息 - 优化圆角样式 -->
		<view class="stats-container">
			<view class="stat-cards">
				<!-- 累计开票金额卡片 -->
				<view class="stat-card">
					<view class="tax-tag">不含税</view>
					<view class="stat-label">
						<view class="marker blue"></view>
						<text>累计开票金额</text>
					</view>
					<text class="stat-value">{{ totalAmount.toFixed(2) }}</text>
				</view>

				<!-- 累计税额卡片 -->
				<view class="stat-card">
					<view class="stat-label">
						<view class="marker orange"></view>
						<text>累计税额</text>
					</view>
					<text class="stat-value">{{ totalTax.toFixed(2) }}</text>
				</view>

				<!-- 开票份数卡片 -->
				<view class="stat-card">
					<view class="stat-label">
						<view class="marker green"></view>
						<text>开票份数</text>
					</view>
					<text class="stat-value">{{ invoiceCount }}</text>
				</view>
			</view>
		</view>

		<!-- 发票列表 -->
		<view class="invoice-list">
			<!-- 空状态 - 图标居中，使用指定图标 -->
			<view v-if="filteredInvoices.length === 0 && isDataLoaded" class="empty-state">
				<u-icon name="file-text" size="60" color="#ccc"></u-icon>
				<text class="empty-text">暂无发票数据</text>
			</view>

			<view class="invoice-item" v-for="(invoice, index) in filteredInvoices" :key="invoice.id">
				<view class="invoice-header">
					<text class="buyer">{{ invoice.buyerLabel }}: {{ invoice.buyerName }}</text>
					<u-icon name="trash" size="24" color="#ff4d4f" class="delete-icon"
						@click.stop="showDeleteConfirm(invoice)"></u-icon>
				</view>
				<view class="invoice-details">
					<view class="detail-row">
						<text class="label">开票日期:</text>
						<text class="value">{{ invoice.invoiceDate }}</text>
					</view>
					<view class="detail-row">
						<text class="label">所属账期:</text>
						<text class="value">{{ invoice.accountPeriod }}</text>
					</view>
					<view class="detail-row">
						<text class="label">开票金额:</text>
						<text class="value">{{ invoice.amount.toFixed(2) }}</text>
					</view>
					<view class="detail-row">
						<text class="label">开票内容:</text>
						<text class="value">{{ invoice.content }}</text>
					</view>
					<!-- 入账时间和同意拒绝按钮在一行 -->
					<view class="detail-row last-row">
						<text class="label">入账期间:</text>
						<text class="value entry-period">{{ invoice.entryPeriod }}</text>
						<u-icon name="edit-pen" size="18" color="#999" class="edit-icon"></u-icon>

						<view class="switch-container">
							<text class="switch-text">拒绝入账</text>
							<u-switch v-model="invoice.rejectEntry" size="24" active-color="#007aff"
								@change="onRejectChange(invoice)">
							</u-switch>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 日期选择器 -->
		<u-picker :show="showDatePicker" :columns="dateColumns" :defaultIndex="defaultDateIndex"
			@confirm="onDateConfirm" @cancel="showDatePicker = false">
		</u-picker>

		<!-- 发票类型选择器 -->
		<u-picker :show="showTypePicker" :columns="typeColumns" @confirm="onTypeConfirm"
			@cancel="showTypePicker = false">
		</u-picker>

		<!-- 底部同步发票按钮 -->
		<view class="fixed-bottom-buttons">
			<view class="btn-container">
				<view class="btn sync-btn" @click="syncInvoices">
					同步发票
				</view>
				<view class="btn camera-btn" @click="handleCameraClick">
					<u-icon name="camera" size="20" color="#fff"></u-icon>
					拍照识别
				</view>
				<view class="btn add-btn" @click="showAddForm = true">
					自定义添加
				</view>
			</view>
		</view>

		<!-- 自定义添加发票弹窗 -->
		<u-popup :show="showAddForm" mode="center" :round="16" :closeOnClickOverlay="false">
			<view class="add-form-container">
				<view class="form-title">添加发票信息</view>

				<view class="form-group">
					<view class="form-label">发票类型</view>
					<view class="form-input" @click="showFormTypePicker = true">
						<text>{{ formData.type || '请选择发票类型' }}</text>
						<u-icon name="arrow-down" size="14" color="#999"></u-icon>
					</view>
				</view>

				<view class="form-group">
					<view class="form-label">所属类别</view>
					<view class="radio-group">
						<view class="radio-item" :class="{ active: formData.category === 0 }"
							@click="formData.category = 0">
							<text>开票</text> <!-- 修复文字错误 -->
						</view>
						<view class="radio-item" :class="{ active: formData.category === 1 }"
							@click="formData.category = 1">
							<text>收票</text> <!-- 修复文字错误 -->
						</view>
						<view class="radio-item" :class="{ active: formData.category === 2 }"
							@click="formData.category = 2">
							<text>费用票</text> <!-- 修复文字错误 -->
						</view>
					</view>
				</view>

				<view class="form-group">
					<view class="form-label">对方单位</view>
					<input type="text" v-model="formData.buyer" class="form-input" placeholder="请输入对方单位名称">
				</view>

				<view class="form-group">
					<view class="form-label">开票日期</view>
					<view class="form-input" @click="showFormDatePicker = true">
						<text>{{ formData.invoiceDate || '请选择开票日期' }}</text>
						<u-icon name="arrow-down" size="14" color="#999"></u-icon>
					</view>
				</view>

				<view class="form-group">
					<view class="form-label">开票金额</view>
					<input type="number" v-model="formData.amount" class="form-input" placeholder="请输入金额">
				</view>

				<view class="form-group">
					<view class="form-label">税额</view>
					<input type="number" v-model="formData.tax" class="form-input" placeholder="请输入税额">
				</view>

				<view class="form-group">
					<view class="form-label">开票内容</view>
					<input type="text" v-model="formData.content" class="form-input" placeholder="请输入开票内容">
				</view>

				<view class="form-actions">
					<view class="form-btn cancel-btn" @click="resetForm">
						取消
					</view>
					<view class="form-btn confirm-btn" @click="submitForm">
						确认添加
					</view>
				</view>
			</view>
		</u-popup>

		<!-- 拍照识别结果预览编辑弹窗 -->
		<u-popup :show="showRecogDialog" @close="handleRecogDialogClose" @open="handleRecogDialogOpen" mode="center"
			:round="16" :closeOnClickOverlay="false">
			<view class="add-form-container">
				<view class="form-title">拍照识别结果（可编辑）</view>
				<!-- 新增：发票图片预览区域 -->
				<view class="invoice-img-container" v-if="uploadedImageUrl">
					<image :src="uploadedImageUrl" mode="aspectFit" class="invoice-thumb-img"
						@click="previewInvoiceImage"></image>
					<text class="img-tip">点击图片可放大预览</text>
				</view>
				<!-- 多发票切换栏 -->
				<view class="recog-switch-bar" v-if="recogInvoicesList.length > 1">
					<view class="switch-btn prev-btn" @click="prevRecogInvoice"
						:class="{disabled: currentRecogIndex === 0}">
						<u-icon name="arrow-left" size="16" color="#fff" />
						上一个
					</view>
					<view class="switch-index">{{ currentRecogIndex + 1 }}/{{ recogInvoicesList.length }}</view>
					<view class="switch-btn next-btn" @click="nextRecogInvoice"
						:class="{disabled: currentRecogIndex === recogInvoicesList.length - 1}">
						下一个
						<u-icon name="arrow-right" size="16" color="#fff" />
					</view>
				</view>

				<view class="form-group">
					<view class="form-label">发票类型</view>
					<view class="form-input" @click="showRecogTypePicker = true">
						<text>{{ recogInvoice.type || '请选择发票类型' }}</text>
						<u-icon name="arrow-down" size="14" color="#999"></u-icon>
					</view>
				</view>

				<view class="form-group">
					<view class="form-label">所属类别</view>
					<view class="radio-group">
						<view class="radio-item" :class="{ active: recogInvoice.category === 0 }"
							@click="recogInvoice.category = 0">
							<text>开票</text>
						</view>
						<view class="radio-item" :class="{ active: recogInvoice.category === 1 }"
							@click="recogInvoice.category = 1">
							<text>收票</text>
						</view>
						<view class="radio-item" :class="{ active: recogInvoice.category === 2 }"
							@click="recogInvoice.category = 2">
							<text>费用票</text>
						</view>
					</view>
				</view>

				<view class="form-group">
					<view class="form-label">对方单位</view>
					<input type="text" v-model="recogInvoice.buyerName" class="form-input" placeholder="请输入对方单位名称">
				</view>

				<view class="form-group">
					<view class="form-label">开票日期</view>
					<view class="form-input" @click="showRecogDatePicker = true">
						<text>{{ recogInvoice.invoiceDate || '请选择开票日期' }}</text>
						<u-icon name="arrow-down" size="14" color="#999"></u-icon>
					</view>
				</view>

				<view class="form-group">
					<view class="form-label">开票金额</view>
					<input type="number" v-model="recogInvoice.amount" class="form-input" placeholder="请输入金额">
				</view>

				<view class="form-group">
					<view class="form-label">税额</view>
					<input type="number" v-model="recogInvoice.taxAmount" class="form-input" placeholder="请输入税额">
				</view>

				<view class="form-group">
					<view class="form-label">开票内容</view>
					<input type="text" v-model="recogInvoice.content" class="form-input" placeholder="请输入开票内容">
				</view>

				<view class="form-actions">
					<view class="form-btn cancel-btn" @click="showRecogDialog = false">取消</view>
					<view class="form-btn confirm-btn" @click="confirmRecogInvoice">确认添加</view>
				</view>
			</view>
		</u-popup>

		<!-- 识别弹窗相关选择器 -->
		<u-picker :show="showRecogTypePicker" :columns="formTypeColumns" @confirm="onRecogTypeConfirm"
			@cancel="showRecogTypePicker = false">
		</u-picker>

		<u-datetime-picker :show="showRecogDatePicker" v-model="recogDateValue" mode="date"
			@confirm="onRecogDateConfirm" @cancel="showRecogDatePicker = false">
		</u-datetime-picker>

		<!-- 表单选择器 -->
		<u-picker :show="showFormTypePicker" :columns="formTypeColumns" @confirm="onFormTypeConfirm"
			@cancel="showFormTypePicker = false">
		</u-picker>

		<u-datetime-picker :show="showFormDatePicker" v-model="formDateValue" mode="date" @confirm="onFormDateConfirm"
			@cancel="showFormDatePicker = false">
		</u-datetime-picker>
		<!-- 新增：删除确认弹窗 -->
		<u-modal :show="showDeleteModal" :title="'删除确认'+currentDeleteName" content="确定要删除该发票吗？删除后不可恢复。"
			:showCancelButton='true' confirmText="删除" cancelText="取消" @confirm="confirmDelete"
			@cancel="showDeleteModal = false" confirmColor="#ff0000" cancelColor="#00aa7f">
		</u-modal>
		<!-- 自定义进度弹窗（替换u-toast） -->
		<view v-if="showProgressModal" class="progress-modal" @click.stop>
			<view class="progress-mask" @click.stop></view>
			<view class="progress-content">
				<!-- 加载动画 -->
				<u-loading-icon :text="progressText" textSize="18"></u-loading-icon>
				<!-- 进度条 -->
				<view class="progress-bar-container">
					<view class="progress-bar-bg">
						<view class="progress-bar" :style="{ width: progressValue + '%' }"></view>
					</view>
					<text class="progress-percent">{{ progressValue }}%</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			// 初始化当前日期为当前年月
			const now = new Date();
			const currentYear = now.getFullYear();
			const currentMonth = now.getMonth() + 1; // 月份从0开始，需要+1
			const currentMonthFormatted = currentMonth.toString().padStart(2, '0');
			const currentDate = `${currentYear}-${currentMonthFormatted}`;

			// 计算默认日期索引（用于日期选择器默认选中当前年月）
			const defaultYearIndex = currentYear - 2020; // 年份从2020开始
			const defaultMonthIndex = currentMonth - 1; // 月份数组从0开始

			return {
				currentDeleteName: '',
				// 新增：删除相关状态
				showDeleteModal: false,
				currentDeleteId: null,
				uploadTask: null, // 保存上传任务实例，用于取消/监听
				uploadedImageUrl: '', // 新增：存储上传的发票图片URL
				// 公司信息
				companyInfo: uni.getStorageSync('companyInfo') || {},
				token: uni.getStorageSync('token'),
				http: uni.$u.http,
				// 标签状态
				currentTab: 0,

				// 核心映射：标签页索引 → 发票categoryId（字符串类型，与接口一致）
				tabToCategoryId: {
					0: '1', // 开出票据 → categoryId=1
					1: '2', // 收到票据 → categoryId=2
					2: '3' // 费用票据 → categoryId=3
				},

				// 搜索关键词
				searchKeyword: '',

				// 筛选状态
				showDatePicker: false,
				showTypePicker: false,
				selectedDate: currentDate, // 默认当前年月
				selectedType: '全部',
				defaultDateIndex: [defaultYearIndex, defaultMonthIndex], // 日期选择器默认索引

				// 日期选择器数据
				dateColumns: [
					(() => {
						const years = [];
						for (let year = 2020; year <= 2030; year++) {
							years.push(year + '年');
						}
						return years;
					})(),
					['01月', '02月', '03月', '04月', '05月', '06月',
						'07月', '08月', '09月', '10月', '11月', '12月'
					]
				],

				// 发票类型数据
				typeColumns: [
					['全部']
				],

				// 发票类型映射关系（id -> 名称）
				invoiceTypeMap: {},
				// 发票类别标签映射（标签页索引 → 对方标签）
				invoiceCategoryLabelMap: {
					0: '购方', // 开出票据 → 购方
					1: '销方', // 收到票据 → 销方
					2: '支付方' // 费用票据 → 支付方
				},

				// 表单类型数据
				formTypeColumns: [
					[]
				],

				// 发票数据（从接口获取）
				invoices: [],

				// 统计数据
				totalAmount: 0,
				totalTax: 0,
				invoiceCount: 0,

				// 数据加载状态
				isDataLoaded: false,

				// 同步状态
				isSyncing: false,

				// 自定义添加表单相关
				showAddForm: false,
				showFormTypePicker: false,
				showFormDatePicker: false,
				formDateValue: Number(new Date()),
				// 拍照识别相关
				showRecogDialog: false,
				recogInvoice: {},
				showRecogTypePicker: false,
				showRecogDatePicker: false,
				recogDateValue: Number(new Date()),
				recogInvoicesList: [],
				currentRecogIndex: 0,
				recogTimeoutTimer: null,
				recogProgressTimer: null, // 识别进度模拟定时器
				recogMaxTime: 300, // 最长等待时间（秒）
				// 表单数据
				formData: {
					type: '',
					typeId: null,
					category: 0, // 标签页索引（0/1/2）
					buyer: '',
					invoiceDate: '',
					amount: '',
					tax: '',
					content: ''
				},

				// 自定义进度弹窗相关（核心新增）
				showProgressModal: false, // 是否显示进度弹窗
				progressText: '', // 进度提示文本
				progressValue: 0 // 进度值（0-100）
			}
		},
		computed: {
			// 获取公司ID
			companyId() {
				return this.companyInfo.id || '';
			},

			// 筛选后的发票列表 - 修复核心映射逻辑
			filteredInvoices() {
				// 当前标签页对应的发票categoryId（字符串类型）
				const targetCategoryId = this.tabToCategoryId[this.currentTab];
				console.log('筛选核心参数：', {
					currentTab: this.currentTab,
					targetCategoryId: targetCategoryId,
					selectedDate: this.selectedDate,
					selectedType: this.selectedType
				});

				const result = this.invoices.filter(invoice => {
					// 1. 核心匹配：发票categoryId（字符串）=== 目标categoryId
					const invoiceCategoryId = invoice.categoryId?.toString() || '';
					if (invoiceCategoryId !== targetCategoryId) {
						return false;
					}

					// 2. 日期筛选：包含年月匹配（兼容2025-11和2025年11月格式）
					if (this.selectedDate) {
						const [year, month] = this.selectedDate.split('-');
						const invoicePeriod = invoice.accountPeriod || invoice.invoiceDate || '';
						if (!invoicePeriod.includes(year) || !invoicePeriod.includes(month)) {
							return false;
						}
					}

					// 3. 类型筛选：匹配发票类型名称
					if (this.selectedType !== '全部') {
						const invoiceTypeName = this.invoiceTypeMap[invoice.typeId?.toString()] || '';
						if (invoiceTypeName !== this.selectedType) {
							return false;
						}
					}

					// 4. 关键词筛选：匹配对方单位、开票内容、日期、金额
					if (this.searchKeyword) {
						const lowerKeyword = this.searchKeyword.toLowerCase();
						const buyerName = (invoice.buyerName || '').toLowerCase();
						const content = (invoice.content || '').toLowerCase();
						const invoiceDate = invoice.invoiceDate || '';
						const amount = (invoice.amount || 0).toString();

						return buyerName.includes(lowerKeyword) ||
							content.includes(lowerKeyword) ||
							invoiceDate.includes(lowerKeyword) ||
							amount.includes(lowerKeyword);
					}

					return true;
				}).map(invoice => ({
					...invoice,
					// 补充对方单位标签（根据标签页索引映射）
					buyerLabel: this.getBuyerLabelByCategoryId(invoice.categoryId),
					// 确保金额为数字类型
					amount: Number(invoice.amount) || 0,
					taxAmount: Number(invoice.taxAmount) || Number(invoice.tax) || 0,
					// 确保拒绝入账状态为布尔值
					rejectEntry: invoice.rejectEntry === 1 || invoice.rejectEntry === true
				}));

				console.log('筛选结果：', result.length, '条数据');
				return result;
			}
		},
		watch: {
			filteredInvoices: {
				handler(newVal) {
					this.updateStatistics(newVal);
				},
				immediate: true
			},
			currentTab: {
				handler() {
					this.loadInvoiceData(); // 切换标签页重新加载
				},
				immediate: true
			},
			companyId: {
				handler(newVal) {
					if (newVal) {
						this.loadInvoiceTypeData();
						this.loadInvoiceData();
					} else {
						this.invoices = [];
						this.invoiceTypeMap = {};
						this.typeColumns = [
							['全部']
						];
						this.formTypeColumns = [
							[]
						];
					}
				},
				immediate: true
			}
		},

		onLoad() {
			this.companyInfo = uni.getStorageSync('companyInfo') || {};
			this.loadInvoiceTypeData();
		},
		onUnload() {
			// 页面卸载时清理所有定时器和上传任务
			this.closeProgressModal();
			if (this.uploadTask) {
				this.uploadTask.abort();
				this.uploadTask = null;
			}
		},
		onShow() {
			if (this.companyId) {
				this.loadInvoiceData(); // 页面显示时刷新数据
			}
		},
		methods: {
			showDeleteConfirm(id) {
				this.currentDeleteId = id.id;
				this.currentDeleteName = id.buyerName;
				this.showDeleteModal = true;
			},

			// 新增：确认删除
			confirmDelete() {
				if (!this.currentDeleteId || !this.companyId) return;

				uni.showLoading({
					title: '删除中...',
					mask: true
				});

				// 调用后端删除接口
				uni.$u.http.delete(`/VipInvoice/${this.currentDeleteId}`)
					.then(res => {
						uni.hideLoading();
						if (res.code === 200) {
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							});
							// 重新加载发票数据
							this.loadInvoiceData();
						} else {
							uni.showToast({
								title: `删除失败：${res.msg || '操作异常'}`,
								icon: 'none'
							});
						}
					})
					.catch(err => {
						uni.hideLoading();
						console.error('删除发票失败：', err);
						uni.showToast({
							title: '删除失败，请重试',
							icon: 'none'
						});
					})
					.finally(() => {
						this.showDeleteModal = false;
						this.currentDeleteId = null;
					});
			},
			// 新增：预览发票图片
			previewInvoiceImage() {
				if (!this.uploadedImageUrl) return;
				uni.previewImage({
					urls: [this.uploadedImageUrl], // 需要预览的图片链接列表
					current: 0, // 当前显示图片的索引
					indicator: 'default', // 显示图片指示器
					loop: false,
					success: (res) => {
						console.log('图片预览成功', res);
					},
					fail: (err) => {
						console.error('图片预览失败', err);
						uni.showToast({
							title: '预览图片失败',
							icon: 'none'
						});
					}
				});
			},
			// ========== 核心修改1：优化发票类型匹配（优先匹配电子发票） ==========
			getMatchedInvoiceType(recogType) {
				// 1. 边界判断：无识别类型或无系统类型时返回空
				if (!recogType || !Object.keys(this.invoiceTypeMap).length) {
					return {
						typeId: '',
						typeName: ''
					};
				}

				// 2. 文本清洗：移除所有非文字/数字字符 + 转小写（最大化匹配成功率）
				const cleanText = (text) => {
					// 保留中文、英文、数字，移除其他所有字符
					return text.toLowerCase().replace(/[^\u4e00-\u9fa5a-zA-Z0-9]/g, '');
				};
				const cleanedRecogType = cleanText(recogType);

				// 3. 动态匹配：遍历后端返回的所有系统类型，做双向包含匹配
				let bestMatch = {
					typeId: '',
					typeName: '',
					matchScore: 0
				};

				Object.entries(this.invoiceTypeMap).forEach(([typeId, typeName]) => {
					const cleanedTypeName = cleanText(typeName);

					// 跳过空的系统类型
					if (!cleanedTypeName) return;

					// 计算匹配分数（优化：优先匹配电子相关关键词）
					let matchScore = 0;

					// 新增：优先规则 - 包含"电子"关键词的类型额外加分（解决电子普通发票匹配问题）
					const hasElectronic = cleanedTypeName.includes('电子');
					if (hasElectronic && cleanedRecogType.includes('电子')) {
						matchScore += 60; // 电子关键词权重提升
					}

					// 规则1：识别类型包含系统类型 → 基础分100
					if (cleanedRecogType.includes(cleanedTypeName)) {
						matchScore += 100;
						// 加分项：字符长度越接近，分数越高（避免短类型匹配到长类型）
						matchScore += 100 - Math.abs(cleanedRecogType.length - cleanedTypeName.length);
					}
					// 规则2：系统类型包含识别类型 → 基础分90（优先级略低）
					else if (cleanedTypeName.includes(cleanedRecogType)) {
						matchScore += 90;
						matchScore += 100 - Math.abs(cleanedRecogType.length - cleanedTypeName.length);
					}
					// 规则3：关键词重叠匹配（拆分字符做交集）
					else {
						const recogChars = new Set(cleanedRecogType.split(''));
						const typeChars = new Set(cleanedTypeName.split(''));
						const intersection = [...recogChars].filter(char => typeChars.has(char));
						// 重叠字符占比 > 60% 则计分
						if (intersection.length / Math.max(recogChars.size, typeChars.size) > 0.6) {
							matchScore = intersection.length * 10;
						}
					}

					// 更新最优匹配
					if (matchScore > bestMatch.matchScore) {
						bestMatch = {
							typeId,
							typeName,
							matchScore
						};
					}
				});

				// 4. 匹配阈值：分数>0才认为匹配成功（避免无效匹配）
				return bestMatch.matchScore > 0 ? {
					typeId: bestMatch.typeId,
					typeName: bestMatch.typeName
				} : {
					typeId: '',
					typeName: ''
				};
			},

			// ========== 核心修改2：替换u-toast为自定义进度弹窗 ==========
			/* // 初始化进度弹窗
			initProgressModal(text, value) {
				this.showProgressModal = true;
				this.progressText = text || '处理中...';
				this.progressValue = value || 0;
			},
			// 更新进度弹窗
			updateProgressModal(text, value) {
				if (this.showProgressModal) {
					this.progressText = text || this.progressText;
					this.progressValue = value || this.progressValue;
				}
			},
			// 关闭进度弹窗
			closeProgressModal() {
				this.showProgressModal = false;
				this.progressText = '';
				this.progressValue = 0;
				// 清除所有定时器
				if (this.recogTimeoutTimer) clearTimeout(this.recogTimeoutTimer);
				if (this.recogProgressTimer) clearInterval(this.recogProgressTimer);
				this.recogTimeoutTimer = null;
				this.recogProgressTimer = null;
			}, */
			// 初始化进度弹窗
			initProgressModal(text, value) {
				this.showProgressModal = true;
				this.progressText = text || '处理中...';
				this.progressValue = value || 0;
			},
			// 更新进度弹窗（限制上传阶段最大80%）
			updateProgressModal(text, value) {
				if (this.showProgressModal) {
					this.progressText = text || this.progressText;
					// 上传阶段限制最大80%，识别阶段从80%开始
					this.progressValue = Math.min(value || this.progressValue, 99); // 最终完成前最大99%
				}
			},
			// 关闭进度弹窗
			closeProgressModal() {
				this.showProgressModal = false;
				this.progressText = '';
				this.progressValue = 0;
				// 清除所有定时器
				if (this.recogTimeoutTimer) clearTimeout(this.recogTimeoutTimer);
				if (this.recogProgressTimer) clearInterval(this.recogProgressTimer);
				this.recogTimeoutTimer = null;
				this.recogProgressTimer = null;
				// 取消上传任务
				if (this.uploadTask) {
					this.uploadTask.abort();
					this.uploadTask = null;
				}
			},

			// ========== 原有方法：替换进度显示逻辑 ==========
			handleCameraClick() {
				const that = this;
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					success(res) {
						const tempFile = res.tempFiles[0];
						that.uploadInvoiceFile(tempFile.path, tempFile);
					},
					fail(err) {
						console.error('选择图片失败', err);
						uni.showToast({
							title: '选择图片失败',
							icon: 'none'
						});
					}
				});
			},

			/* uploadInvoiceFile(tempFilePath, tempFile) {
				const uploadUrl = uni.$u.http.config.baseURL + 'oss/upload';
				const that = this;

				// 初始化自定义进度弹窗
				this.initProgressModal('开始上传...', 0);

				try {
					this.http.upload(uploadUrl, {
						filePath: tempFilePath,
						name: 'file',
						header: {
							'SA-TOKEN-USER': this.token,
							'Content-Type': 'multipart/form-data'
						},
						getTask: (requestTask) => {
							requestTask.onProgressUpdate((res) => {
								const progress = res.progress || 0;
								console.log('上传进度:', progress + '%');
								// 更新自定义进度弹窗
								this.updateProgressModal(
									progress < 100 ? `上传中：${progress}%` : '上传完成，开始识别...' +
									`${progress}%`,
									progress
								);
							});
						}
					}).then((res) => {
						console.log('图片上传返回结果:', res);
						if (res.code === 200 && res.data) {
							// 上传成功，过渡到识别阶段
							this.updateProgressModal('识别中...', 90);
							uni.showToast({
								title: '文件上传成功',
								icon: 'none',
								duration: 1500
							});
							that.callInvoiceRecogApi(res.data);
						} else {
							this.closeProgressModal(); // 失败关闭弹窗
							uni.showToast({
								title: `上传失败：${res.msg || '接口返回异常'}`,
								icon: 'none'
							});
						}
					}).catch((err) => {
						console.error('图片上传异常:', err);
						this.closeProgressModal(); // 异常关闭弹窗
						uni.showToast({
							title: '上传失败，请重试',
							icon: 'none'
						});
					});
				} catch (err) {
					console.error('上传方法执行异常:', err);
					this.closeProgressModal(); // 异常关闭弹窗
					uni.showToast({
						title: '上传失败，请重试',
						icon: 'none'
					});
				}
			},
 */
			uploadInvoiceFile(tempFilePath, tempFile) {
				const uploadUrl = uni.$u.http.config.baseURL + 'oss/upload';
				const that = this;
				// 初始化自定义进度弹窗（上传阶段从0开始）
				this.initProgressModal('开始上传...', 0);

				try {
					this.uploadTask = this.http.upload(uploadUrl, {
						filePath: tempFilePath,
						name: 'file',
						header: {
							'SA-TOKEN-USER': this.token,
							'Content-Type': 'multipart/form-data'
						},
						getTask: (requestTask) => {
							// 保存上传任务实例
							this.uploadTask = requestTask;
							// 监听进度更新
							requestTask.onProgressUpdate((res) => {
								// 核心修复：上传进度最大限制为80%，避免提前到100%
								let progress = Math.min(res.progress || 0, 80);
								console.log('上传进度:', progress + '%');
								// 更新自定义进度弹窗
								this.updateProgressModal(
									`上传中：${progress}%`,
									progress
								);
							});
						}
					}).then((res) => {
						console.log('图片上传返回结果:', res);
						if (res.code === 200 && res.data) {
							// 新增：保存上传的图片URL
							this.uploadedImageUrl = res.data;
							// 上传完成，进入识别阶段（进度从80开始）
							this.updateProgressModal('上传完成，开始识别...', 80);
							// 延迟1秒再调用识别接口，让用户感知上传完成
							setTimeout(() => {
								that.callInvoiceRecogApi(res.data);
							}, 500);
						} else {
							this.closeProgressModal(); // 失败关闭弹窗
							uni.showToast({
								title: `上传失败：${res.msg || '接口返回异常'}`,
								icon: 'none'
							});
						}
					}).catch((err) => {
						console.error('图片上传异常:', err);
						this.closeProgressModal(); // 异常关闭弹窗
						uni.showToast({
							title: '上传失败，请重试',
							icon: 'none'
						});
					});
				} catch (err) {
					console.error('上传方法执行异常:', err);
					this.closeProgressModal(); // 异常关闭弹窗
					uni.showToast({
						title: '上传失败，请重试',
						icon: 'none'
					});
				}
			},
			/* callInvoiceRecogApi(imageUrl) {
				const that = this;
				this.closeProgressModal(); // 先清空旧定时器

				// 初始化识别进度弹窗
				this.initProgressModal('识别中...', 0);

				// 模拟识别进度（提升用户感知）
				let recogProgress = 0;
				this.recogProgressTimer = setInterval(() => {
					recogProgress += Math.floor(Math.random() * 10) + 5; // 随机增加5-15%
					if (recogProgress >= 95) recogProgress = 95; // 保留5%到识别完成
					this.updateProgressModal(`识别中：${recogProgress}%`, recogProgress);
				}, 1000);

				// 超时逻辑
				this.recogTimeoutTimer = setTimeout(() => {
					this.closeProgressModal();
					uni.showToast({
						title: '识别超时失败',
						icon: 'none'
					});
				}, this.recogMaxTime * 1000);

				uni.$u.http.post('/api/image/invoice', {}, {
					params: {
						imageUrl: imageUrl
					} // imageUrl拼接为URL参数
				}).then(res => {
					// 识别完成，更新进度为100%
					this.updateProgressModal('识别完成', 100);
					// 延迟关闭，让用户看到完成状态
					setTimeout(() => {
						this.closeProgressModal();
					}, 500);

					if (res.code === 200 && res.data) {
						that.parseInvoiceRecogResult(res.data);
						that.showRecogDialog = true;
					} else {
						uni.showToast({
							title: '识别失败',
							icon: 'none'
						});
					}
				}).catch(err => {
					this.closeProgressModal();
					console.error('识别接口调用失败:', err);
					uni.showToast({
						title: '识别失败',
						icon: 'none'
					});
				});
			},
 */
			callInvoiceRecogApi(imageUrl) {
				const that = this;
				// 清空旧定时器（防止叠加）
				if (this.recogProgressTimer) clearInterval(this.recogProgressTimer);
				if (this.recogTimeoutTimer) clearTimeout(this.recogTimeoutTimer);

				// 识别阶段初始进度80%
				let recogProgress = 80;
				// 识别进度递增（每500ms增加1-3%，直到99%）
				this.recogProgressTimer = setInterval(() => {
					recogProgress += Math.floor(Math.random() * 3) + 1;
					if (recogProgress >= 99) recogProgress = 99; // 最大99%，直到接口返回
					this.updateProgressModal(`识别中：${recogProgress}%`, recogProgress);
				}, 500);

				// 超时逻辑
				this.recogTimeoutTimer = setTimeout(() => {
					this.closeProgressModal();
					uni.showToast({
						title: '识别超时失败',
						icon: 'none'
					});
				}, this.recogMaxTime * 1000);

				uni.$u.http.post('/api/image/invoice', {}, {
					params: {
						imageUrl: imageUrl
					} // imageUrl拼接为URL参数
				}).then(res => {
					// 识别完成，进度跳至100%
					this.updateProgressModal('识别完成', 100);
					// 延迟关闭，让用户看到完成状态
					setTimeout(() => {
						this.closeProgressModal();
					}, 800);

					if (res.code === 200 && res.data) {
						that.parseInvoiceRecogResult(res.data);
						that.showRecogDialog = true;
					} else {
						uni.showToast({
							title: '识别失败',
							icon: 'none'
						});
					}
				}).catch(err => {
					this.closeProgressModal();
					console.error('识别接口调用失败:', err);
					uni.showToast({
						title: '识别失败',
						icon: 'none'
					});
				});
			},
			parseInvoiceRecogResult(recogData) {
				const today = new Date();
				const year = today.getFullYear();
				const month = (today.getMonth() + 1).toString().padStart(2, '0');
				const day = today.getDate().toString().padStart(2, '0');
				const dateStr = `${year}-${month}-${day}`;

				this.recogInvoicesList = Array.isArray(recogData) ? recogData : (recogData.data ? recogData.data : [
					recogData
				]);
				this.currentRecogIndex = 0;

				if (this.recogInvoicesList.length > 0) {
					const currentItem = this.recogInvoicesList[0];
					this.recogInvoice = {
						type: currentItem.type || '',
						typeId: '',
						category: 0,
						buyerName: currentItem.buyerName || '',
						invoiceDate: currentItem.invoiceDate || dateStr,
						amount: currentItem.amount || '',
						taxAmount: currentItem.taxAmount || '',
						content: currentItem.content || '',
						accountPeriod: currentItem.invoiceDate ? currentItem.invoiceDate.split('-').slice(0, 2).join(
							'-') : `${year}-${month}`,
						entryPeriod: `${year}-${month}`
					};

					// 使用优化后的动态模糊匹配（优先电子发票）
					if (this.recogInvoice.type) {
						const matched = this.getMatchedInvoiceType(this.recogInvoice.type);
						if (matched.typeId) {
							this.recogInvoice.typeId = matched.typeId;
							this.recogInvoice.type = matched.typeName; // 统一为系统标准名称
						} else {
							uni.showToast({
								title: `未匹配到"${this.recogInvoice.type}"对应的发票类型，请手动选择`,
								icon: 'none',
								duration: 3000
							});
						}
					}
				} else {
					this.recogInvoice = {
						type: '',
						typeId: '',
						category: 0,
						buyerName: '',
						invoiceDate: dateStr,
						amount: '',
						taxAmount: '',
						content: '',
						accountPeriod: `${year}-${month}`,
						entryPeriod: `${year}-${month}`
					};
				}
			},

			prevRecogInvoice() {
				if (this.currentRecogIndex > 0) {
					this.currentRecogIndex--;
					this.updateCurrentRecogInvoice();
				}
			},

			nextRecogInvoice() {
				if (this.currentRecogIndex < this.recogInvoicesList.length - 1) {
					this.currentRecogIndex++;
					this.updateCurrentRecogInvoice();
				}
			},

			updateCurrentRecogInvoice() {
				const currentItem = this.recogInvoicesList[this.currentRecogIndex];
				const invoiceDate = currentItem.invoiceDate || this.recogInvoice.invoiceDate;
				const yearMonth = invoiceDate.split('-').slice(0, 2).join('-');

				this.recogInvoice = {
					...this.recogInvoice,
					type: currentItem.type || '',
					buyerName: currentItem.buyerName || '',
					invoiceDate: invoiceDate,
					amount: currentItem.amount || '',
					taxAmount: currentItem.taxAmount || '',
					content: currentItem.content || '',
					accountPeriod: yearMonth
				};

				// 使用优化后的动态模糊匹配
				if (this.recogInvoice.type) {
					const matched = this.getMatchedInvoiceType(this.recogInvoice.type);
					if (matched.typeId) {
						this.recogInvoice.typeId = matched.typeId;
						this.recogInvoice.type = matched.typeName;
					}
				}
			},

			// ========== 其他原有方法均不变 ==========
			handleRecogDialogOpen() {
				this.recogDateValue = new Date(this.recogInvoice.invoiceDate || new Date());
			},

			handleRecogDialogClose() {
				this.showRecogDialog = false;
				this.showRecogTypePicker = false;
				this.showRecogDatePicker = false;
				this.uploadedImageUrl = ''; // 新增：关闭弹窗时清空图片URL
			},

			onRecogTypeConfirm(e) {
				const typeName = e.value[0];
				const typeId = Object.keys(this.invoiceTypeMap).find(key => this.invoiceTypeMap[key] === typeName);
				this.recogInvoice.type = typeName;
				this.recogInvoice.typeId = typeId;
				this.showRecogTypePicker = false;
			},

			onRecogDateConfirm(e) {
				const date = new Date(e.value);
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				this.recogInvoice.invoiceDate = `${year}-${month}-${day}`;
				this.recogInvoice.accountPeriod = `${year}-${month}`;
				this.showRecogDatePicker = false;
			},

			confirmRecogInvoice() {
				if (!this.companyId) return uni.showToast({
					title: '请先选择公司',
					icon: 'none'
				});
				if (!this.recogInvoice.typeId) return uni.showToast({
					title: '请选择发票类型',
					icon: 'none'
				});
				if (!this.recogInvoice.buyerName.trim()) return uni.showToast({
					title: '请输入对方单位',
					icon: 'none'
				});
				if (!this.recogInvoice.invoiceDate) return uni.showToast({
					title: '请选择开票日期',
					icon: 'none'
				});
				const amount = parseFloat(this.recogInvoice.amount);
				if (isNaN(amount) || amount <= 0) return uni.showToast({
					title: '请输入有效金额',
					icon: 'none'
				});

				const newInvoice = {
					companyId: this.companyId,
					categoryId: this.tabToCategoryId[this.recogInvoice.category],
					typeId: this.recogInvoice.typeId,
					buyerName: this.recogInvoice.buyerName.trim(),
					invoiceDate: this.recogInvoice.invoiceDate,
					accountPeriod: this.recogInvoice.accountPeriod,
					amount: amount,
					taxAmount: this.recogInvoice.taxAmount ? parseFloat(this.recogInvoice.taxAmount) : 0,
					content: this.recogInvoice.content.trim() || '无',
					entryPeriod: this.recogInvoice.accountPeriod,
					rejectEntry: 0,
					remark: '拍照识别添加'
				};

				uni.showLoading({
					title: '提交中...',
					mask: true
				});
				uni.$u.http.post('/VipInvoice', newInvoice).then(res => {
					uni.hideLoading();
					if (res.code === 200) {
						uni.showToast({
							title: '添加成功',
							icon: 'success'
						});
						this.showRecogDialog = false;
						this.loadInvoiceData();
						if (this.currentRecogIndex < this.recogInvoicesList.length - 1) {
							this.nextRecogInvoice();
							this.showRecogDialog = true;
						}
					} else {
						uni.showToast({
							title: '添加失败',
							icon: 'none'
						});
					}
				}).catch(err => {
					uni.hideLoading();
					console.error('添加失败：', err);
					uni.showToast({
						title: '添加失败',
						icon: 'none'
					});
				});
			},

			formatSelectedDate() {
				if (!this.selectedDate) return '';
				const [year, month] = this.selectedDate.split('-');
				return `${year}年${month}月`;
			},

			switchTab(index) {
				this.currentTab = index;
			},

			getBuyerLabelByCategoryId(categoryId) {
				const tabIndex = Object.keys(this.tabToCategoryId).find(key => this.tabToCategoryId[key] === categoryId
					?.toString());
				return this.invoiceCategoryLabelMap[tabIndex] || '对方单位';
			},

			loadInvoiceTypeData() {
				if (!this.companyId) return;

				uni.$u.http.get('/VipInvoiceType/list', {
					params: {
						companyId: this.companyId,
						pageSize: 100
					}
				}).then(res => {
					if (res.code === 200 && res.data.data) {
						const typeList = res.data.data;
						this.invoiceTypeMap = typeList.reduce((map, type) => {
							map[type.id.toString()] = type.typeName;
							return map;
						}, {});
						const typeNames = typeList.map(type => type.typeName);
						this.typeColumns = [
							['全部', ...typeNames]
						];
						this.formTypeColumns = [
							[...typeNames]
						];
						console.log('加载发票类型成功：', typeNames);
					} else {
						this.typeColumns = [
							['全部']
						];
						this.formTypeColumns = [
							[]
						];
					}
				}).catch(err => {
					console.error('加载发票类型失败：', err);
					uni.showToast({
						title: '加载发票类型失败',
						icon: 'none'
					});
				});
			},

			loadInvoiceData() {
				if (!this.companyId) {
					this.invoices = [];
					this.isDataLoaded = true;
					return;
				}

				this.isDataLoaded = false;
				uni.showLoading({
					title: '加载中...',
					mask: true
				});

				const params = {
					companyId: this.companyId,
					categoryCode: this.tabToCategoryId[this.currentTab],
					pageSize: 1000
				};
				if (this.selectedDate) params.accountPeriod = this.selectedDate;
				if (this.selectedType !== '全部') {
					const typeId = Object.keys(this.invoiceTypeMap).find(key => this.invoiceTypeMap[key] === this
						.selectedType);
					if (typeId) params.typeId = typeId;
				}

				uni.$u.http.get('/VipInvoice/list', {
					params
				}).then(res => {
					uni.hideLoading();
					this.isDataLoaded = true;
					if (res.code === 200 && res.data.data) {
						this.invoices = res.data.data;
					} else {
						this.invoices = [];
					}
				}).catch(err => {
					uni.hideLoading();
					this.isDataLoaded = true;
					this.invoices = [];
					console.error('加载发票失败：', err);
					uni.showToast({
						title: '加载发票失败',
						icon: 'none'
					});
				});
			},

			onDateConfirm(e) {
				const year = e.value[0].replace('年', '');
				const month = e.value[1].replace('月', '');
				this.selectedDate = `${year}-${month}`;
				this.showDatePicker = false;
				this.loadInvoiceData();
			},

			onTypeConfirm(e) {
				this.selectedType = e.value[0];
				this.showTypePicker = false;
				this.loadInvoiceData();
			},

			updateStatistics(invoices) {
				this.totalAmount = invoices.reduce((sum, item) => sum + item.amount, 0);
				this.totalTax = invoices.reduce((sum, item) => sum + item.taxAmount, 0);
				this.invoiceCount = invoices.length;
			},

			onRejectChange(invoice) {
				const newStatus = invoice.rejectEntry ? 1 : 0;
				uni.$u.http.put('/VipInvoice', {
					id: invoice.id,
					companyId: this.companyId,
					rejectEntry: newStatus
				}).then(res => {
					if (res.code === 200) {
						uni.showToast({
							title: newStatus === 1 ? '已拒绝入账' : '已允许入账',
							icon: 'none'
						});
					} else {
						invoice.rejectEntry = !invoice.rejectEntry;
						uni.showToast({
							title: '操作失败',
							icon: 'none'
						});
					}
				}).catch(err => {
					invoice.rejectEntry = !invoice.rejectEntry;
					console.error('更新状态失败：', err);
					uni.showToast({
						title: '操作失败',
						icon: 'none'
					});
				});
			},

			handleSearch() {
				uni.showToast({
					title: '搜索完成',
					icon: 'none'
				});
			},

			handleExport() {
				if (!this.companyId || this.invoiceCount === 0) {
					return uni.showToast({
						title: '暂无数据可导出',
						icon: 'none'
					});
				}

				uni.showLoading({
					title: '导出中...',
					mask: true
				});
				const params = {
					companyId: this.companyId,
					categoryCode: this.tabToCategoryId[this.currentTab],
					accountPeriod: this.selectedDate,
					typeId: this.selectedType !== '全部' ?
						Object.keys(this.invoiceTypeMap).find(key => this.invoiceTypeMap[key] === this.selectedType) :
						''
				};

				uni.$u.http.get('/VipInvoice/export', {
					params,
					responseType: 'blob'
				}).then(res => {
					uni.hideLoading();
					const blob = new Blob([res.data], {
						type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
					});
					const url = window.URL.createObjectURL(blob);
					const a = document.createElement('a');
					a.href = url;
					a.download = `发票数据_${this.companyId}_${new Date().getTime()}.xlsx`;
					document.body.appendChild(a);
					a.click();
					window.URL.revokeObjectURL(url);
					document.body.removeChild(a);
					uni.showToast({
						title: '导出成功',
						icon: 'none'
					});
				}).catch(err => {
					uni.hideLoading();
					console.error('导出失败：', err);
					uni.showToast({
						title: '导出失败',
						icon: 'none'
					});
				});
			},

			syncInvoices() {
				if (this.isSyncing || !this.companyId) return;
				this.isSyncing = true;
				uni.showToast({
					title: '正在同步...',
					icon: 'loading',
					duration: 10000,
					mask: true
				});

				uni.$u.http.post('/VipInvoice/sync', {
					companyId: this.companyId
				}).then(res => {
					this.isSyncing = false;
					uni.hideToast();
					if (res.code === 200) {
						uni.showToast({
							title: '同步成功',
							icon: 'success'
						});
						this.loadInvoiceData();
					} else {
						uni.showToast({
							title: '同步失败',
							icon: 'none'
						});
					}
				}).catch(err => {
					this.isSyncing = false;
					uni.hideToast();
					console.error('同步失败：', err);
					uni.showToast({
						title: '同步失败',
						icon: 'none'
					});
				});
			},

			onFormTypeConfirm(e) {
				const typeName = e.value[0];
				const typeId = Object.keys(this.invoiceTypeMap).find(key => this.invoiceTypeMap[key] === typeName);
				this.formData.type = typeName;
				this.formData.typeId = typeId;
				this.showFormTypePicker = false;
			},

			onFormDateConfirm(e) {
				const date = new Date(e.value);
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				this.formData.invoiceDate = `${year}-${month}-${day}`;
				this.showFormDatePicker = false;
			},

			resetForm() {
				this.formData = {
					type: '',
					typeId: null,
					category: 0,
					buyer: '',
					invoiceDate: '',
					amount: '',
					tax: '',
					content: ''
				};
				this.showAddForm = false;
			},

			submitForm() {
				if (!this.companyId) return uni.showToast({
					title: '请先选择公司',
					icon: 'none'
				});
				if (!this.formData.typeId) return uni.showToast({
					title: '请选择发票类型',
					icon: 'none'
				});
				if (!this.formData.buyer.trim()) return uni.showToast({
					title: '请输入对方单位',
					icon: 'none'
				});
				if (!this.formData.invoiceDate) return uni.showToast({
					title: '请选择开票日期',
					icon: 'none'
				});
				const amount = parseFloat(this.formData.amount);
				if (isNaN(amount) || amount <= 0) return uni.showToast({
					title: '请输入有效金额',
					icon: 'none'
				});

				const newInvoice = {
					companyId: this.companyId,
					categoryId: this.tabToCategoryId[this.formData.category],
					typeId: this.formData.typeId,
					buyerName: this.formData.buyer.trim(),
					invoiceDate: this.formData.invoiceDate,
					accountPeriod: this.formData.invoiceDate.split('-').slice(0, 2).join('-'),
					amount: amount,
					taxAmount: this.formData.tax ? parseFloat(this.formData.tax) : 0,
					content: this.formData.content.trim() || '无',
					entryPeriod: this.formData.invoiceDate.split('-').slice(0, 2).join('-'),
					rejectEntry: 0,
					remark: '手动添加'
				};

				uni.showLoading({
					title: '提交中...',
					mask: true
				});
				uni.$u.http.post('/VipInvoice', newInvoice).then(res => {
					uni.hideLoading();
					if (res.code === 200) {
						uni.showToast({
							title: '添加成功',
							icon: 'success'
						});
						this.resetForm();
						this.loadInvoiceData();
					} else {
						uni.showToast({
							title: '添加失败',
							icon: 'none'
						});
					}
				}).catch(err => {
					uni.hideLoading();
					console.error('添加失败：', err);
					uni.showToast({
						title: '添加失败',
						icon: 'none'
					});
				});
			}
		}
	};
</script>
<style lang="scss" scoped>
	.content {
		background: #ffffff;
		min-height: 100vh;
		box-sizing: border-box;
	}

	/* 导航栏样式 */
	.navbar-left {
		.nav-back-content {
			display: flex;
			align-items: center;

			.nav-title {
				font-size: 34rpx;
				font-weight: 500;
				color: #1e88e5;
				margin-left: 16rpx;
			}
		}
	}

	.navbar-right {
		display: flex;
		align-items: center;
	}

	/* 搜索框样式 */
	.search-container {
		padding: 16rpx 30rpx;
		background-color: #fff;
		border-bottom: 1px solid #f5f5f5;

		.search-box {
			display: flex;
			align-items: center;
			background-color: #f5f5f5;
			border-radius: 60rpx;
			padding: 14rpx 24rpx;

			.search-icon {
				margin-right: 12rpx;
			}

			.search-input {
				flex: 1;
				font-size: 28rpx;
				color: #333;
				background: transparent;
				border: none;
				outline: none;
				height: 36rpx;
				line-height: 36rpx;
			}

			.search-input::placeholder {
				color: #999;
			}
		}
	}

	/* 标签页样式 */
	.custom-tabs {
		display: flex;
		border-bottom: 1px solid #eee;
		background-color: #fff;

		.tab-item {
			flex: 1;
			text-align: center;
			padding: 28rpx 0;
			font-size: 32rpx;
			color: #333;
			position: relative;

			&.active {
				color: #1677ff;
				font-weight: 500;

				&::after {
					content: '';
					position: absolute;
					bottom: 0;
					left: 0;
					width: 100%;
					height: 4rpx;
					background-color: #1677ff;
				}
			}
		}
	}

	/* 筛选栏 */
	.filter-container {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 24rpx 30rpx;
		background: #fff;
		border-bottom: 1px solid #eee;

		.filter-left {
			display: flex;
			align-items: center;

			.date-filter,
			.type-filter {
				display: flex;
				align-items: center;
				font-size: 28rpx;
				color: #333;
				padding: 8rpx 16rpx;

				u-icon {
					margin-left: 8rpx;
					margin-top: 2rpx;
				}
			}

			.type-filter {
				margin-left: 30rpx;
			}
		}

		.filter-right {
			display: flex;
			align-items: center;

			.search-btn,
			.export-btn {
				font-size: 28rpx;
				color: #333;
				padding: 8rpx 16rpx;
			}

			.export-btn {
				margin-left: 30rpx;
			}
		}
	}

	/* 统计信息 - 优化圆角 */
	.stats-container {
		padding: 24rpx 30rpx;
		background: #fff;

		.stat-cards {
			display: flex;
			gap: 16rpx;
			width: 100%;
		}

		.stat-card {
			flex: 1;
			background-color: #f9f9f9;
			border-radius: 16rpx;
			padding: 20rpx;
			position: relative;
			min-height: 140rpx;
			box-sizing: border-box;
			overflow: hidden;

			.tax-tag {
				position: absolute;
				top: 0;
				left: 0;
				background-color: #ff7d00;
				color: #fff;
				font-size: 22rpx;
				padding: 2rpx 8rpx;
				border-radius: 0 0 16rpx 0;
				z-index: 1;
				line-height: 1.4;
			}

			.stat-label {
				display: flex;
				align-items: center;
				font-size: 24rpx;
				color: #666;
				margin-bottom: 10rpx;
				padding-top: 28rpx;

				.marker {
					width: 12rpx;
					height: 12rpx;
					border-radius: 50%;
					margin-right: 6rpx;
				}

				.blue {
					background-color: #1677ff;
				}

				.orange {
					background-color: #ff7d00;
				}

				.green {
					background-color: #00b42a;
				}
			}

			.stat-value {
				font-size: 36rpx;
				color: #333;
				font-weight: 500;
				line-height: 1.2;
			}
		}
	}

	/* 发票列表 */
	.invoice-list {
		background-color: #fff;
		padding: 16rpx 30rpx;
		padding-bottom: 170rpx;

		.invoice-item {
			background: #fff;
			border-radius: 28rpx;
			padding: 24rpx;
			margin-bottom: 16rpx;
			border: 1px solid #f0f0f0;
			box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.03);

			.invoice-header {
				margin-bottom: 20rpx;

				.buyer {
					font-size: 30rpx;
					color: #333;
					font-weight: 500;
				}
			}

			.invoice-details {
				border-left: 2rpx solid #eee;
				padding-left: 20rpx;

				.detail-row {
					display: flex;
					align-items: center;
					font-size: 26rpx;
					color: #666;
					line-height: 1.8;

					&.last-row {
						justify-content: space-between;
					}

					.label {
						color: #999;
						min-width: 160rpx;
					}

					.value {
						color: #333;
						text-align: left;
						flex: 1;
					}

					.entry-period {
						margin-right: 10rpx;
					}

					.edit-icon {
						margin-right: 20rpx;
					}
				}

				.switch-container {
					display: flex;
					align-items: center;
					margin-left: auto;
				}

				.switch-text {
					font-size: 26rpx;
					color: #666;
					margin-right: 10rpx;
				}
			}
		}

		.empty-state {
			text-align: center;
			padding: 100rpx 0;
			color: #999;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;

			u-icon {
				margin-bottom: 20rpx;
			}

			.empty-text {
				display: block;
				font-size: 28rpx;
			}
		}
	}

	/* 底部按钮区域 */
	.fixed-bottom-buttons {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		padding: 30rpx 30rpx 50rpx 30rpx;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
		z-index: 10;

		.btn-container {
			width: 100%;
			display: flex;
			gap: 16rpx;
		}

		.btn {
			flex: 1;
			height: 88rpx;
			line-height: 88rpx;
			text-align: center;
			border-radius: 16rpx;
			font-size: 32rpx;
			font-weight: 500;
		}

		.sync-btn {
			background-color: #1677ff;
			color: #fff;
		}

		.camera-btn {
			background-color: #4096ff;
			color: #fff;
			display: flex;
			justify-content: center;
			align-items: center;
			gap: 8rpx;
		}

		.add-btn {
			background-color: #00b42a;
			color: #fff;
		}
	}

	/* 自定义添加表单样式 */
	.add-form-container {
		background: #fff;
		border-radius: 16rpx;
		padding: 40rpx;
		width: 700rpx;
		max-width: 90vw;
		box-sizing: border-box;
	}

	.form-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		text-align: center;
		margin-bottom: 40rpx;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.form-group {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;

		.form-label {
			width: 160rpx;
			font-size: 28rpx;
			color: #333;
			font-weight: 500;
		}

		.form-input {
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 20rpx 24rpx;
			border: 1rpx solid #e0e0e0;
			border-radius: 8rpx;
			font-size: 28rpx;
			color: #333;
			background: #fff;

			input {
				flex: 1;
				font-size: 28rpx;
				color: #333;
				border: none;
				outline: none;
				background: transparent;
			}

			input::placeholder {
				color: #999;
			}
		}

		.radio-group {
			flex: 1;
			display: flex;
			gap: 16rpx;

			.radio-item {
				flex: 1;
				text-align: center;
				padding: 20rpx;
				border: 1rpx solid #e0e0e0;
				border-radius: 8rpx;
				font-size: 26rpx;
				color: #666;
				transition: all 0.3s;

				&.active {
					border-color: #1677ff;
					color: #1677ff;
					background: #f0f8ff;
					font-weight: 500;
				}
			}
		}
	}

	.form-actions {
		display: flex;
		gap: 20rpx;
		margin-top: 40rpx;
		padding-top: 30rpx;
		border-top: 1rpx solid #f0f0f0;

		.form-btn {
			flex: 1;
			text-align: center;
			padding: 24rpx;
			border-radius: 8rpx;
			font-size: 32rpx;
			font-weight: 500;
		}

		.cancel-btn {
			background: #f5f5f5;
			color: #666;
		}

		.confirm-btn {
			background: #1677ff;
			color: #fff;
		}
	}

	page {
		background-color: #ffffff;
		height: 100%;
	}

	/* 识别弹窗切换栏样式 */
	.recog-switch-bar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 12rpx 16rpx;
		background-color: #f5f7fa;
		border-radius: 8rpx;
		margin-bottom: 20rpx;
	}

	.switch-btn {
		display: flex;
		align-items: center;
		gap: 4rpx;
		padding: 6rpx 12rpx;
		border-radius: 6rpx;
		background-color: #1677ff;
		color: white;
		font-size: 26rpx;
		cursor: pointer;

		&.disabled {
			background-color: #cccccc;
			color: #999999;
			cursor: not-allowed;
		}
	}

	.switch-index {
		font-size: 26rpx;
		color: #666;
		font-weight: 500;
	}

	/* 自定义进度弹窗样式（核心） */
	/* 进度弹窗样式 - 兼容低版本，确保遮罩覆盖全屏禁止滚动 */
	.progress-modal {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 9999;
		display: flex;
		align-items: center;
		justify-content: center;
		overflow: hidden;

		.progress-mask {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			background-color: rgba(0, 0, 0, 0.5);
		}

		.progress-content {
			position: relative;
			z-index: 1;
			background-color: #fff;
			border-radius: 16rpx;
			padding: 40rpx 30rpx;
			width: 600rpx;
			text-align: center;
		}

		.progress-bar-container {
			margin-top: 30rpx;
			width: 100%;
		}

		.progress-bar-bg {
			height: 12rpx;
			background-color: #f0f0f0;
			border-radius: 6rpx;
			overflow: hidden;
		}

		.progress-bar {
			height: 100%;
			background-color: #1677ff;
			border-radius: 6rpx;
			transition: width 0.3s ease;
		}

		.progress-percent {
			display: block;
			margin-top: 10rpx;
			font-size: 24rpx;
			color: #666;
		}
	}

	/* .progress-modal {
		position: fixed;
		top: 0;
		left: 0;
		width: 100vw;
		height: 100vh;
		z-index: 9999;
		display: flex;
		justify-content: center;
		align-items: center;
	} */

	.progress-mask {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5);
	}

	.progress-content {
		position: relative;
		width: 600rpx;
		background-color: #fff;
		border-radius: 16rpx;
		padding: 40rpx 30rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 20rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.15);
	}

	.loading-icon {
		animation: spin 1s linear infinite;
	}

	@keyframes spin {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}

	.progress-text {
		font-size: 30rpx;
		color: #333;
		font-weight: 500;
	}

	.progress-bar-container {
		width: 100%;
		display: flex;
		flex-direction: column;
		gap: 10rpx;
	}

	.progress-bar-bg {
		width: 100%;
		height: 12rpx;
		background-color: #f5f5f5;
		border-radius: 6rpx;
		overflow: hidden;
	}

	.progress-bar {
		height: 100%;
		background-color: #1677ff;
		border-radius: 6rpx;
		transition: width 0.3s ease;
	}

	.progress-percent {
		font-size: 24rpx;
		color: #666;
		text-align: right;
	}

	/* 新增：发票图片预览样式 */
	.invoice-img-container {
		padding: 20rpx;
		text-align: center;

		.invoice-thumb-img {
			width: 100%;
			height: 200rpx;
			border-radius: 8rpx;
			margin-bottom: 10rpx;
		}

		.img-tip {
			font-size: 24rpx;
			color: #999;
		}
	}

	.invoice-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;

		.delete-icon {
			cursor: pointer;
		}
	}
</style>